<?php

namespace app\models;

use yii\db\ActiveRecord;

/**
 * 卡短信
 * Class CardSms
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $card_id 卡编号
 * @property integer $type 类型
 * @property integer $time 时间
 * @property string $msg_id 消息流水号
 * @property string $content 内容
 * @property integer $status 状态
 * @property string $info 状态信息
 * @property string $remark 备注
 *
 * @property Card $card 关联卡
 */
class CardSms extends ActiveRecord
{
    const TYPE_DOWN = 1; // 下行
    const TYPE_UP = 2; // 上行

    const STATUS_WAIT = 1; // 待发送
    const STATUS_PAUSE = 2; // 暂停发送
    const STATUS_SEND = 3; // 提交成功
    const STATUS_FAIL = 4; // 提交失败
    const STATUS_DELIVRD = 5; // 发送成功
    const STATUS_UNDELIV = 6; // 发送失败

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['content', 'required'],
        ];
    }

    /**
     * 关联卡
     * @return \yii\db\ActiveQuery
     */
    public function getCard()
    {
        return $this->hasOne(Card::class, ['id' => 'card_id']);
    }

    /**
     * 发送短信
     * @param $card Card 卡
     * @param $content string 内容
     * @throws ApiException
     */
    public static function send($card, $content)
    {
        $sms = new CardSms();
        $sms->card_id = $card->id;
        $sms->type = CardSms::TYPE_DOWN;
        $sms->time = time();
        $sms->content = $content;
        $sms->status = CardSms::STATUS_WAIT;
        if (!$sms->save()) {
            throw new ApiException('SERVER', '无法保存短信。', $sms->errors);
        }
        if ($card->api_id == 1) { // Jasper接口
            // TODO:
        } elseif ($card->api_id == 2 || $card->api_id == 3) { // 山东移动或中移接口
            (new ActiveMqApi('/queue/cmpp3-submit'))->send([
                'sms_id' => $sms->id,
                'card_id' => $card->id,
                'msisdn' => $card->msisdn,
                'sms_ignore_sign' => $card->sms_ignore_sign,
                'content' => $content,
            ]);
        }
    }
}
